<template>
  <div>
    <div class="container_main">
      <!-- 地图 -->
      <div class="container_left">
        <div class="nanjingCard">
          <div class="title">南京直属</div>
          <div class="content">
            <div class="up">上调能力:{{ nanjingData.up }}</div>
            <div class="down">下调能力:{{ nanjingData.lower }}</div>
            <div class="num">资源个数:{{ nanjingData.num }}</div>
          </div>
        </div>

        <div class="tab-panel">
          <div v-for="(item, index) in mapTabList" :key="index" @click="selMapTabOption(item)">
            <span class="option-btn" :class="{ btnSelected: item.isActive }">{{ item.text }}</span>
          </div>
        </div>
        <div class="map-panel">
          <div style="width: 135px;height: 100%;">
            <div class="timeline">
              <el-timeline style="width: 100%">
                <el-timeline-item v-for="(activity, index) in timeLineList" style="cursor: pointer" :class="[
                  index == currentHour ? 'timeline-wrap2' : 'timeline-wrap',
                ]" size="large" color="#ccc" :timestamp="activity.timestamp">

                  <div :class="[
                    activity.type == '0'
                      ? 'timeline-abs'
                      : activity.type == '1'
                        ? 'timeline-abs abs-red'
                        : 'timeline-abs abs-yellow',
                  ]"></div>
                  <img v-if="activity.status == '1'" src="@/assets/images/icon-top.png" class="timeline-icon" />
                  <img v-if="activity.status == '2'" src="@/assets/images/icon-bottom.png" class="timeline-icon" />
                </el-timeline-item>
              </el-timeline>

              <template>
                <el-slider class="myslider" @input="handleSliderInput" @change="handleSliderChange"
                  v-model="sliderValue" :min="min" :max="max" :show-tooltip="false" vertical></el-slider>
                <div class="mytooltip" v-if="showCustomTooltip" :style="{ top: customTooltipTop }">
                  {{ customTooltipText }}
                </div>
              </template>
            </div>

            <div class="timeline-legend" style="width: 100%;margin-top: 10px;">
              <div class="status1">越限</div>
              <div class="status2">重载</div>
              <div class="type1">正向</div>
              <div class="type2">反向</div>
            </div>
          </div>

          <div style="width: 980px;height: 90%" id="map" ref="map"></div>
        </div>

      </div>
      <!-- 右边部分 -->
      <div class="container_right">
        <!--上边部分-->
        <div class="container_top">
          <div class="part-top">
            <div class=" part part2">
              <div class="flex-row">
                <img class="row-img" src="~@/assets/images/raise.png">
                <div class="row-data">
                  <div class="row-info">
                    <span>{{ total_UpAdjustEnergy }}</span><span style="font-size: 14px;">MW</span>
                  </div>
                  <div class="row-title">总上调能力</div>
                </div>
              </div>
              <div class="flex-row">
                <img class="row-img" src="~@/assets/images/down.png">
                <div class="row-data">
                  <div class="row-info">
                    <span>{{ total_DownAdjustEnergy }}</span><span style="font-size: 14px;">MW</span>
                  </div>
                  <div class="row-title">总下调能力</div>
                </div>
              </div>
            </div>
            <div class="part part3">
              <div class="title">
                可调资源能力占比
                <span> 单位:MW</span>

                <el-dropdown @command="chartsCenterNameEvt" size="mini" style="margin-left: 60px;" split-button>
                  {{ chartsCenterName }}
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item></el-dropdown-item>
                    <el-dropdown-item command="上调节能力">上调节能力</el-dropdown-item>
                    <el-dropdown-item command="下调节能力">下调节能力</el-dropdown-item>
                    <el-dropdown-item command="总可调电力">总可调电力</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div style="width: 100%;height: calc(100% - 35px); " id="ktzyChart" ref="ktzyChart"></div>
            </div>
          </div>
          <div class="part-bottom">
            <div class="part part1">
              <div class="title">分类型可调节能力<span>单位:MW</span></div>
              <div style="width: 100%;height: calc(100% - 35px); " id="phydChart" ref="phydChart"></div>
            </div>
          </div>
        </div>
        <!--下边图表-->
        <div class="container_bottom">
          <div class="part4">
            <div class="title">可调节资源<span>单位:MW</span></div>
            <div style="width: 100%;height: calc(100% - 50px);padding: 10px;">
              <el-table max-height="360px" :cell-style="{ border: '1px solid #0C8F96', height: '35px' }"
                :row-style="setRowClass" :header-row-style="{ height: '45px' }"
                :header-cell-style="{ 'border-radius': 0, border: '1px solid #0C8F96', 'background-color': 'rgba(117,215,225,0.2)', 'text-align': 'center', 'font-size': '16px', color: '#17274A', 'font-weight': 'bold' }"
                :data="dataList" v-loading="dataListLoading" style="width: 99.5%;" ref="table">
                <el-table-column type="index" header-align="center" align="center" label="序号"></el-table-column>
                <el-table-column prop="resource_name" header-align="center" align="center"
                  label="资源名称"></el-table-column>
                <el-table-column prop="resource_type" header-align="center" align="center"
                  label="资源类型"></el-table-column>
                <el-table-column prop="margin_up" header-align="center" align="center" label="上可调能力"></el-table-column>
                <el-table-column prop="margin_down" header-align="center" align="center"
                  label="下可调能力"></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <div class="chart-float" v-if="popupShow">
        <div class="title">

          <el-dropdown trigger="click" @command="selectChangeEvt">
            <span class="el-dropdown-link">
              {{ popupTitle }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="it.name" v-for="it in selectData" :key="it.name">{{ it.name
                }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span class="close" @click="popupChartClose()">X</span>
        </div>
        <!-- 点击柱子之后echarts -->
        <div class="chart" id="popupChart" ref="popupChart">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import mock from '@/utils/home/home.mockdata.js';
import { recose_type, duiyingGx } from './diqv'
import homeMap from "@/utils/home/home.map";

import { getCurrentInstance } from 'vue'
import {
  seriousDevice,
  getYxPoints,
  adjustResourceAbilityByLine,
  timeAxis,
  getYxInfoByDvId,
  adjustResourceByTime,
  momentSerious,
  adjustResource,
  adjustResourceAbility,
  adjustResourceMap,
  adjustResourceMapByTime,
  adjustResourceAbilityByTime,
  mapForLine,
} from "@/api/index";
export default {
  name: "resource-city",
  data() {
    return {
      min: -96,
      max: 0, //00:00-24:00
      sliderValue: 0,
      customTooltipTop: "0%",
      showCustomTooltip: false,
      phyjShowDate: false,
      symbolSizes: null,
      timeLineList: mock.resource_timelineList, // 时间轴

      nanjingData: {
        up: 650,
        lower: 798,
        num: 122,
      },

      centerDialogVisible: true,
      chartsCenterName: '总可调电力',

      upData_myData: false,
      selectData: [
      ],

      dateTimeX: [],
      mapParams: {
        type: 6,
        dateTime: '',
      },

      typeKadjustParams: {
        resourceType: '',
      },
      map_chartsMap: {
        areaId: '',
        type: 1,
      },
      total_UpAdjustEnergy: 735,
      total_DownAdjustEnergy: 1125,
      currentHour: 0,
      timeNow: 0,
      is_clickTimeline: false,
      mapTabList: [
        { text: '总加', id: 0, isActive: true },
        { text: '储', id: 1, isActive: false },
        { text: '源', id: 2, isActive: false },
        { text: '荷', id: 3, isActive: false },
        { text: '新能源', id: 4, isActive: false }
      ],

      timeLineList: mock.resource_timelineList,
      phydChart: undefined,

      phydChartOption: {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          top: "6%",
          type: "plain",
          data: ["上调能力", "下调能力"],
        },
        grid: {
          left: "3%",
          right: "6%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: ["储", "源", "荷", "新能源"],
          axisLabel: {
            interval: 0, // 设置间隔显示
            margin: 10, // 设置文字与轴线的距离
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "上调能力",
            type: "bar",
            data: [120, 132, 101, 134],
            barGap: "20%",
            barWidth: 14,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#92c9be" },
                { offset: 1, color: "#408d95" },
              ]),
            },
          },
          {
            name: "下调能力",
            type: "bar",
            data: [220, 182, 191, 234],
            barGap: "20%",
            barWidth: 14,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#F4B066" },
                { offset: 1, color: "#F49044" },
              ]),
            },
          }
        ],
      },
      ktzyChart: undefined,
      ktzyChartOption: {
        color: ['#478BF0', '#00B4FF', '#74ACEB', '#5FBD96', '#ADBCDA'],

        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        grid: {
          left: "3%",
          right: "6%",
          top: "100%",
          bottom: "3%",
          // containLabel: true,
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['50%', '65%'],
            // avoidLabelOverlap: false,
            padAngle: 15,
            itemStyle: {
              borderWidth: 4, //扇区间加间隔
              borderColor: '#ffffff', //间隔为白色
              //borderRadius: 10
            },
            label: {
              show: true,
              position: 'outside',
              alignTo: 'edge',
              formatter: '{name|{b}}:{rate|{d}%}\n{val|{c} MW}',
              minMargin: 5,
              edgeDistance: 30,
              lineHeight: 20,
              rich: {
                name: {
                  fontSize: 14,
                  color: '#222'
                },
                rate: {
                  fontSize: 14,
                  color: '#222'
                },
                val: {
                  fontSize: 12,
                  color: '#666'
                }
              }
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 0,
              minTurnAngle: 120,
              maxSurfaceAngle: 180,
              lineStyle: {
                type: 'dashed',
                cap: 'round'
              },
              /*length: 15,
              length2: 10,
              maxSurfaceAngle: 80*/
            },
            labelLayout: function (params) {
              const isLeft = params.labelRect.x < 380 / 2;
              const points = params.labelLinePoints;
              // Update the end point.
              points[2][0] = isLeft
                ? params.labelRect.x
                : params.labelRect.x + params.labelRect.width;
              return {
                labelLinePoints: points
              };
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            data: [
              { value: 635, name: '储' },
              { value: 520, name: '源' },
              { value: 484, name: '荷' },
              { value: 400, name: '新能源' }
            ]
          }
        ]
      },
      mapJson: {},
      mapChart: undefined,
      mapChartOption: {
        toolbox: {
          show: true,
          orient: 'vertical',
          left: 'right',
          top: 'center'
        },
        series: [
          {
            name: '资源详情',
            type: 'map',
            z: 1,
            map: this.$store.state.home.mapCity,
            label: {
              show: true,
              color: '#ffffff'
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10,
              minTurnAngle: 90,
              maxSurfaceAngle: 180,
              lineStyle: {
                type: 'dashed',
                cap: 'round'
              },
              /*length: 15,
              length2: 10,
              maxSurfaceAngle: 80*/
            },
            itemStyle: {
              normal: { // 静态的时候显示的默认样式
                borderWidth: 1, // 边框宽度
                areaColor: {
                  type: "linear",
                  x: 0.5,
                  y: 0.5,
                  r: 0.9,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#59bcc2", // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#82CBBE", // 100% 处的颜色
                    },
                  ],
                  globalCoord: false, // 缺省为 false
                },
                borderColor: '#ffffff' // 边框颜色
              },
              emphasis: { // 鼠标移入动态的时候显示的默认样式
                borderWidth: 2, // 边框宽度
                areaColor: '#0979A9' // 地图颜色
              }
            },
            data: []
          },
        ],
        geo: {
          geoIndex: 1,
          map: 'nanjing',
          label: {
            show: false
          },
          zoom: 1
        }
      },
      dataList: [
        { index: 1, resource_name: '储能', resource_type: '储', margin_up: '22', margin_down: '20' },
        { index: 2, resource_name: '非统调电源', resource_type: '源', margin_up: '20', margin_down: '0' },
        { index: 3, resource_name: '统调电源', resource_type: '源', margin_up: '90', margin_down: '0' },
        { index: 4, resource_name: '可调负荷', resource_type: '荷', margin_up: '10', margin_down: '0' },
        { index: 5, resource_name: '虚拟电厂', resource_type: '荷', margin_up: '630', margin_down: '15' },
        { index: 6, resource_name: '微电网', resource_type: '荷', margin_up: '100', margin_down: '23' },
        { index: 7, resource_name: '统调集中式新能源', resource_type: '新能源', margin_up: '10', margin_down: '9' },
        { index: 8, resource_name: '非统调集中式新能源', resource_type: '新能源', margin_up: '0', margin_down: '0' },
        { index: 9, resource_name: '调度分布式新能源', resource_type: '新能源', margin_up: '85', margin_down: '8' },
      ],
      dataListLoading: false,
      popupTitle: '',
      popupShow: false,
      popupChart: undefined,
      popupChartOption: {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          top: "6%",
          type: "plain",
          data: ["上调能力", "下调能力"],
        },
        grid: {
          left: "3%",
          right: "6%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: ["00:15", "05:00", "09:45", "14:30", "19:15", "24:00"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "上调能力",
            type: "line",
            smooth: true,
            symbolSize: 0,
            data: [120, 132, 101, 134, 90, 120],
          },
          {
            name: "下调能力",
            type: "line",
            smooth: true,
            symbolSize: 0,
            data: [220, 182, 191, 234, 290, 220],
          }
        ],
      },
    };
  },
  computed: {
    mapCity: {
      get() { return 'nanjing' },
    },
    customTooltipText() {
      let hour = ("00" + Math.floor(Math.abs(this.sliderValue) / 4)).slice(-2);
      let mm = ("00" + (Math.abs(this.sliderValue) % 4) * 15).slice(-2);
      return `${hour}:${mm}`;
    },
  },
  created() {

    //生成X时间轴
    for (let i = 0; i < 24; i++) {
      let a;
      if (i < 10) {
        a = "0" + i;
      } else {
        a = i.toString();
      }
      for (let j = 1; j < 5; j++) {
        let b = (j * 15).toString();
        if (b === "60") {
          a =
            i < 10
              ? "0" + (Number(a) + 1).toString()
              : (Number(a) + 1).toString();
          b = "00";
        }
        this.dateTimeX.push(a + ":" + b);
      }
    }


    this.$emit("balance-reload");
    this.timeNow = this.getLast15Minutes(new Date());
    this.currentHour = new Date().getHours();

    this.useMytimeAxis() //时间轴

    this.useMyadjustResource()//可调节资源

    this.useMyadjustResourceAbility() // 柱状图 换状图

    this.useMyMap()  // 地图板块



  },
  mounted() {
    //初始化时间标签
    const now = new Date();
    const hour = now.getHours();
    const minutes = now.getMinutes();
    this.sliderValue = -Math.floor((hour * 60 + minutes) / 15);


    //柱状图
    this.phydChart = echarts.init(this.$refs.phydChart);
    this.phydChartOption && this.phydChart.setOption(this.phydChartOption);
    //柱子加鼠标事件
    this.phydChart.on("click", (params) => {
      this.popupTitle = params.name + '可调节能力曲线';

      if (params.name == '储') {
        this.selectData = [
          { name: "储" },
          { name: "储能" },
        ]
      } else if (params.name == '源') {
        this.selectData = [
          { name: "源" },
          { name: "非统调电源" },
          { name: "统调电源" },
        ]

      } else if (params.name == '荷') {
        this.selectData = [
          { name: "荷" },
          { name: "可调负荷" },
          { name: "虚拟电厂" },
          { name: "微电网" },
        ]

      } else {
        this.selectData = [
          { name: "新能源" },
          { name: "统调集中式新能源" },
          { name: "非统调集中式新能源" },
          { name: "调度分布式新能源" },
        ]
      }


      recose_type.forEach(it => {
        if (it.name == params.name) {
          this.typeKadjustParams.resourceType = it.value
        }
      })

      console.log(params.name);

      this.useMyadjustResourceAbilityByLine()

    })
    // .on("mouseout",(params2)=>{
    //   this.popupShow=false;
    // });
    //饼图
    this.ktzyChart = echarts.init(this.$refs.ktzyChart);
    var centerImg = require("../../../assets/images/pie-bg.png");
    var graphic1 = [
      {
        type: "image",
        id: "piebg",
        left: "center", //调整图片位置
        top: "center", //调整图片位置
        z: -10,//确保图片在饼图下方
        //设置图片样式
        style: {
          image: centerImg,
          width: 100,
          height: 100,
          //width: this.ktzyChart.getWidth() - 105,
          //height: this.ktzyChart.getHeight() - 105,
          opacity: 1,
        },
      },
      {
        //环形图中间添加文字
        type: "text", //通过不同top值可以设置上下显示
        left: "center",
        top: "center",
        style: {
          text: '总可调电力',
          textAlign: "center",
          fill: "#2D3B4D", //文字的颜色
          lineHeight: 15,
          fontSize: 14,
          fontWeight: '400',
          fontFamily: "Microsoft YaHei"
        }
      },
    ];
    this.ktzyChartOption.graphic = graphic1;
    this.ktzyChartOption && this.ktzyChart.setOption(this.ktzyChartOption);
    //地图
    this.mapJson = require("@/utils/home/mapJson/" + this.mapCity + ".json");
    //地图
    echarts.registerMap(this.mapCity, this.mapJson);
    this.mapChart = echarts.init(this.$refs.map);

    //点击事件
    // this.mapChart.on("click", (params) => {
    //   if (params.seriesIndex == 1) {//点击卡片弹出图表

    //     this.popupTitle = params.name + '可调节能力';

    //     this.map_chartsMap.type = this.mapParams.type
    //     this.map_chartsMap.areaId = duiyingGx(params.name)

    //     this.useMymapForLine()

    //   }
    // });
    this.initMymap()

    this.useMyMap() //更新地图要放在后面

  },
  methods: {
    handleSliderInput(val) {
      this.sliderValue = val;
      this.sliderPosition();
    },
    handleSliderChange(val) {
      //加载数据
      // this.mapInfo.time = this.customTooltipText;

      this.dataList.forEach(it => {
        it.margin_up = this.getRandomInt(10, 30)
        it.margin_down = this.getRandomInt(10, 30)
        this.total_UpAdjustEnergy = this.getRandomInt(1110, 1030)
        this.total_DownAdjustEnergy = this.getRandomInt(1000, 1030)
      })

      this.currentHour = this.customTooltipText;
      this.timeNow = this.customTooltipText;
      this.is_clickTimeline = true

      console.log(this.timeNow, '时间');
      this.mapParams.dateTime = this.timeNow

      this.useMyadjustResourceAbility()  //分类型可调节能力
      this.useMyadjustResource()  // 可调节资源

      this.useMyMap() //地图板块
      this.selMapTabOption()



    },
    sliderPosition() {
      /*const tooltipPosition =
          ((Math.abs(this.sliderValue) / 96) * 100).toFixed(2)*/
      const tooltipPosition = (Math.abs(this.sliderValue) / 96) * 720; //因为el-slider的高度是720
      this.customTooltipTop = `calc(${tooltipPosition}px - 6px)`; //减去黑点的1/2高度
      this.showCustomTooltip = true;
    },


    chartsCenterNameEvt(it) {
      console.log(it);

      this.chartsCenterName = it

      console.log(this.ktzyChartOption.graphic[1].style.text = it);

      this.useMyadjustResourceAbility()

    },

    // 柱状图上的折线中的下拉框
    selectChangeEvt(command, event) {
      this.popupTitle = command + '可调节能力曲线';
      console.log(command, 'iiiiiiii');

      recose_type.forEach(it => {
        if (it.name == command) {
          this.typeKadjustParams.resourceType = it.value
        }
      })
      this.useMyadjustResourceAbilityByLine()
    },

    // 更新地图上的折线图
    useMymapForLine() {

      mapForLine(this.map_chartsMap).then(res => {
        if (res.code !== 200) return
        let xData = []
        let upData = []
        let downData = []
        res.data.margin_down.forEach(it => {
          xData.push(it.x)
          downData.push(it.y)
        })

        res.data.margin_up.forEach(it => {
          upData.push(it.y)
        })

        this.popupShow = true;
        this.$nextTick(() => {
          this.popupChart = echarts.init(this.$refs.popupChart);
          this.popupChart.clear();
          this.popupChartOption && this.popupChart.setOption(this.popupChartOption);
        });
      })
    },


    // 可调节资源
    useMyadjustResource() {
      if (!this.is_clickTimeline) {
        adjustResource().then(res => {
          if (res.code !== 200) return
          res.data.forEach(it => {
            it.margin_down = Number(it.margin_down).toFixed(2)
            it.margin_up = Number(it.margin_up).toFixed(2)

            recose_type.forEach(et => {
              if (it.resource_type == et.value) {
                it.resource_type = et.name
              }
            })
          })
          this.dataList = res.data
        })
      } else {
        adjustResourceByTime(this.mapParams).then(res => {
          if (res.code !== 200) return
          res.data.forEach(it => {
            it.margin_down = Number(it.margin_down).toFixed(2)
            it.margin_up = Number(it.margin_up).toFixed(2)
            recose_type.forEach(et => {
              if (it.resource_type == et.value) {
                it.resource_type = et.name
              }
            })
          })
          this.dataList = res.data
        })
      }
    },

    //分类型可调节能力   柱状图  饼图
    useMyadjustResourceAbility() {

      if (!this.is_clickTimeline) {

        adjustResourceAbility().then(res => {

          res.data = res.data.filter(it => {
            return it.resource_type != null
          })

          let sortArray = ["储", "源", "荷", "新能源"]

          res.data.sort((a, b) => {
            return sortArray.indexOf(a.resource_type) - sortArray.indexOf(b.resource_type)
          })

          console.log(res.data, '看一下更新后的data');

          let UpTotal = 0
          let DownTotal = 0

          res.data.forEach(it => {
            UpTotal += it.margin_up,
              DownTotal += it.margin_down
          })

          console.log(UpTotal, DownTotal, 'totoal');

          this.total_DownAdjustEnergy = Number(DownTotal).toFixed(2) || '未知'
          this.total_UpAdjustEnergy = Number(UpTotal).toFixed(2) || '未知'

          let newUpData = []
          let newDownData = []

          res.data.forEach(it => {
            newUpData.push(Number(it.margin_up).toFixed(2))
            newDownData.push(Number(it.margin_down).toFixed(2))
          })

          this.phydChartOption.series[0].data = newUpData
          this.phydChartOption.series[1].data = newDownData


          this.$nextTick(() => {
            //柱状图
            this.phydChart = echarts.init(this.$refs.phydChart);
            this.phydChartOption && this.phydChart.setOption(this.phydChartOption);
          })


          console.log(this.ktzyChartOption.series[0].data[0].value, '柱状图');

          if (this.chartsCenterName == '总可调电力') {
            console.log('总可调电力')

            this.ktzyChartOption.series[0].data[0].value = res.data[0].margin_up + res.data[0].margin_down

            this.ktzyChartOption.series[0].data[1].value = res.data[1].margin_up + res.data[1].margin_down

            this.ktzyChartOption.series[0].data[2].value = res.data[2].margin_up + res.data[2].margin_down

            this.ktzyChartOption.series[0].data[3].value = res.data[3].margin_up + res.data[3].margin_down

          } else if (this.chartsCenterName == '上调节能力') {
            console.log('上调节能力')
            this.ktzyChartOption.series[0].data[0].value = res.data[0].margin_up

            this.ktzyChartOption.series[0].data[1].value = res.data[1].margin_up

            this.ktzyChartOption.series[0].data[2].value = res.data[2].margin_up

            this.ktzyChartOption.series[0].data[3].value = res.data[3].margin_up

          } else {
            console.log('下可调电力')
            this.ktzyChartOption.series[0].data[0].value = res.data[0].margin_down

            this.ktzyChartOption.series[0].data[1].value = res.data[1].margin_down

            this.ktzyChartOption.series[0].data[2].value = res.data[2].margin_down

            this.ktzyChartOption.series[0].data[3].value = res.data[3].margin_down

          }

          this.ktzyChartOption.series[0].data.forEach(it => {
            it.value = Number(it.value).toFixed(2)
          })


          console.log(this.ktzyChartOption.series[0].data[0], '柱状图');

          let ZeroData = this.ktzyChartOption.series[0].data

          if (ZeroData[0].value == 0 && ZeroData[1].value == 0 && ZeroData[2].value == 0 && ZeroData[3].value == 0) {
            this.ktzyChartOption.series[0].label.formatter =
              '{name|{b}}:{rate|{0}%}\n{val|{c} MW}'
          } else {
            this.ktzyChartOption.series[0].label.formatter =
              '{name|{b}}:{rate|{d}%}\n{val|{c} MW}'
          }


          this.$nextTick(() => {
            //饼图
            this.ktzyChart = echarts.init(this.$refs.ktzyChart);
            this.ktzyChartOption && this.ktzyChart.setOption(this.ktzyChartOption);
          })

        })
      } else {
        adjustResourceAbilityByTime(this.mapParams).then(res => {

          res.data = res.data.filter(it => {
            return it.resource_type != null
          })

          let sortArray = ["储", "源", "荷", "新能源"]

          res.data.sort((a, b) => {
            return sortArray.indexOf(a.resource_type) - sortArray.indexOf(b.resource_type)
          })

          console.log(res.data, '看一下更新后的data');

          let UpTotal = 0
          let DownTotal = 0

          res.data.forEach(it => {
            UpTotal += it.margin_up,
              DownTotal += it.margin_down
          })

          console.log(UpTotal, DownTotal, 'totoal');
          this.total_DownAdjustEnergy = Number(DownTotal).toFixed(2) || '未知'
          this.total_UpAdjustEnergy = Number(UpTotal).toFixed(2) || '未知'


          let newUpData = []
          let newDownData = []

          res.data.forEach(it => {
            newUpData.push(Number(it.margin_up).toFixed(2))
            newDownData.push(Number(it.margin_down).toFixed(2))
          })

          this.phydChartOption.series[0].data = newUpData
          this.phydChartOption.series[1].data = newDownData


          this.$nextTick(() => {
            //柱状图
            this.phydChart = echarts.init(this.$refs.phydChart);
            this.phydChartOption && this.phydChart.setOption(this.phydChartOption);
          })
          console.log(this.ktzyChartOption.series[0].data[0].value, '柱状图');
          this.ktzyChartOption.series[0].data[0].value = res.data[0].margin_up + res.data[0].margin_down

          this.ktzyChartOption.series[0].data[1].value = res.data[1].margin_up + res.data[1].margin_down

          this.ktzyChartOption.series[0].data[2].value = res.data[2].margin_up + res.data[2].margin_down

          this.ktzyChartOption.series[0].data[3].value = res.data[3].margin_up + res.data[3].margin_down

          this.ktzyChartOption.series[0].data.forEach(it => {
            it.value = Number(it.value).toFixed(2)
          })
          console.log(this.ktzyChartOption.series[0].data, '柱状图');
          this.$nextTick(() => {
            //饼图
            this.ktzyChart = echarts.init(this.$refs.ktzyChart);
            this.ktzyChartOption && this.ktzyChart.setOption(this.ktzyChartOption);
          })

        })

      }
    },

    // 生成 min 到 max 之间的随机整数
    getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },

    // 修改时间后触发的方法
    changeTimeEvt(it, time, buttonType, index) {

      this.dataList.forEach(it => {
        it.margin_up = this.getRandomInt(10, 30)
        it.margin_down = this.getRandomInt(10, 30)
        this.total_UpAdjustEnergy = this.getRandomInt(1110, 1030)
        this.total_DownAdjustEnergy = this.getRandomInt(1000, 1030)

      })

      this.currentHour = it.timestamp.slice(0, 2);
      this.timeNow = this.addMinutesToTime(it.timestamp, time);
      this.is_clickTimeline = true

      console.log(this.timeNow, '时间');
      this.mapParams.dateTime = this.timeNow

      this.useMyadjustResourceAbility()  //分类型可调节能力
      this.useMyadjustResource()  // 可调节资源

      this.useMyMap() //地图板块
      this.selMapTabOption()

    },
    processData(data) {
      return data.reduce((result, obj) => {
        for (let key in obj) {
          const [num, color] = obj[key].split('_');
          if (!result[key] || parseFloat(num) > parseFloat(result[key].split('_')[0])) {
            result[key] = obj[key];
          }
        }
        return result;
      }, {});
    },

    generateArrayFromObject(obj) {
      const result = [];
      for (const timestamp in obj) {
        const [value, status, type] = obj[timestamp].split('||');
        const [, color] = value.split('_');

        const newItem = {
          timestamp,
          type: type === '0' ? '1' : '2',
          status: color === 'red' ? '1' : color === 'yellow' ? '2' : '0'
        };
        result.push(newItem);
      }
      return result;
    },


    // // 时间轴
    useMytimeAxis() {
      timeAxis().then(res => {

        res.data.forEach(it => {
          for (let k in it) {
            it[k] = it[k] + "||" + it.over_type
          }
        })

        res.data.forEach(it => {
          delete it.dev_id
          delete it.dev_name
          delete it.dev_p
          delete it.dev_se
          delete it.over_type
          delete it.threshold
        })

        let myObject = this.generateArrayFromObject(this.processData(res.data))

        this.timeLineList.forEach(it => {
          myObject.forEach(et => {
            if (it.timestamp == et.timestamp) {
              it.status = et.type
              it.type = et.status
              // it.type = et.type
              // it.status = et.status
            }
          })
        })
      })
    },


    // 拼接时间的方法
    addMinutesToTime(timeStr, minutes) {
      // 将时间字符串拆分成小时和分钟部分
      const [hours, minutesStr] = timeStr.split(":");
      const minutesNum = parseInt(minutesStr, 10);
      // 将分钟部分加上 30 分钟
      const newMinutes = (minutesNum + minutes) % 60;
      // 计算新的小时部分
      const newHours =
        parseInt((minutesNum + minutes) / 60, 10) + parseInt(hours, 10);
      // 将更新后的小时和分钟部分重新拼接成新的时间字符串
      return `${String(newHours).padStart(2, "0")}:${String(
        newMinutes
      ).padStart(2, "0")}`;
    },


    getLast15Minutes(currentTime) {
      if (!currentTime) {
        var time = new Date();
      }
      var time = new Date(currentTime); // 创建一个当前时间的副本
      // 获取当前时间的分钟数
      var minutes = time.getMinutes();
      // 计算上一个15分钟时间节点的分钟数
      var last15Minutes = Math.floor(minutes / 15) * 15;
      // 设置时间的分钟数为上一个15分钟时间节点的分钟数
      time.setMinutes(last15Minutes);
      time.setSeconds(0); // 确保秒数为0，避免误差
      var h = time.getHours();
      var m = time.getMinutes();
      if (m < 10) {
        m = "0" + m;
      }
      return h + ":" + m;
    },



    initMymap() {
      let parentMapJson = require('@/utils/home/mapJson/nanjing.json');
      let cityItem = parentMapJson.features.find((x) => x.properties.name == "玄武区");  //这边这个位置应该不能写死

      let cityCenter = cityItem.properties.center;
      let resDatas = this.mapJson.features.map((item) => {

        // console.log(item.properties.center[0], '看位置');
        // console.log(item.properties.center[0],'看0的位置');

        item.name = item.properties.name;
        item.coords = [
          item.properties.center,
          [item.properties.center[0] < 118.786088 ? item.properties.center[0] + (Math.random() * 0.9 + 0.4) : item.properties.center[0] - (Math.random() * 0.8 + 0.5),
          item.properties.center[1]
          ]
        ]
        item.info = {
          up: 20,
          lower: 20,
          num: 40
        };
        return item;
      });

      // let nanjing = JSON.parse(JSON.stringify(resDatas[8]))   // 这里添加一个南京的值
      // nanjing.name = '南京'
      // // nanjing.coords
      // resDatas.push(nanjing)
      // console.log(resDatas, '看位置');

      let opt = {
        type: 'lines',
        z: 3,
        coordinateSystem: 'geo',
        symbol: 'circle',
        symbolSize: [5, 0],//只保留地图端标记
        opacity: 1,
        label: {
          show: true,
          position: 'end',
          formatter: function (params) {//文本提示框
            return '{title|' + params.name + '}\n{hr|}\n{value| 上调能力：' + params.data.info.up + '}\n{value| 下调能力：' + params.data.info.lower + '}\n{value| 资源个数：' + params.data.info.num + '}'
          },
          backgroundColor: '#eee',
          /*borderColor: '#00706B',*/
          borderWidth: 1,
          borderRadius: 4,
          align: 'center',
          width: 100,
          rich: { //标题样式
            title: {
              align: 'center',
              lineHeight: 26,
              fontSize: 16,
              fontWeight: '400',
              color: '#2D3B4D',
              backgroundColor: '#bce0e1',
              width: 100,
              height: 26,
              borderRadius: [4, 4, 0, 0]
            },
            hr: {
              borderColor: '#777',
              width: '100%',
              borderWidth: 0.5,
              align: 'left',
              height: 0
            },
            value: { //内容样式
              height: 22,
              width: 100,
              color: '#3a4a5e',
              backgroundColor: '#c8f0f0',
              borderRadius: [0, 0, 4, 4]
            }
          }
        },
        lineStyle: { //视觉引导线属性
          type: 'dashed',
          opacity: 1,
          color: '#414346', //引导线颜色
          // curveness: 0.1
        },
        data: resDatas
      };
      console.log(resDatas, 'resDatasresDatasresDatas');
      this.mapChart.clear(),  // 清除地图上的挂件
        this.mapChartOption.series.push(opt);
      this.mapChart.setOption(this.mapChartOption);
    },

    // 分类型可调节能力------折线图
    useMyadjustResourceAbilityByLine() {
      adjustResourceAbilityByLine(this.typeKadjustParams).then(res => {
        if (res.code !== 200) return
        let xData = []
        let upData = []
        let downData = []

        res.data.margin_up.forEach((it) => {
          xData.push(it.x)
          upData.push(Number(it.y).toFixed(2))
        })

        res.data.margin_down.forEach((it) => {
          // xData.push(it.x)
          downData.push(Number(it.y).toFixed(2))
        })

        console.log(xData, '上下xData');
        console.log(upData, '上下upData');
        console.log(downData, "上下downData");

        this.popupChartOption.series[0].data = upData
        this.popupChartOption.series[1].data = downData
        this.popupChartOption.xAxis.data = xData

        this.popupShow = true;
        //渲染柱状图 点击之后的折线图
        this.$nextTick(() => {
          this.popupChart = echarts.init(this.$refs.popupChart);
          this.popupChart.clear();
          this.popupChartOption && this.popupChart.setOption(this.popupChartOption);
        });
      })
    },


    selMapTabOption(data) {

      if (!data.isActive) {
        this.mapTabList.forEach(function (obj) {
          obj.isActive = false;
        });
        data.isActive = true;
      }


      if (data.text == '总加') {
        this.mapParams.type = 6
      }
      if (data.text == '储') {
        this.mapParams.type = 4
      }
      if (data.text == '源') {
        this.mapParams.type = 1
      }
      if (data.text == '荷') {
        this.mapParams.type = 3
      }
      if (data.text == '新能源') {
        this.mapParams.type = 5
      }

      // // 调用总加的方法
      // console.log(this.mapChartOption.series[1].data, '看地图');
      // console.log(sortArray, '看地图');
      // 地图板块  不加时间版本
      this.useMyMap()

    },

    // 地图板块

    useMyMap() {
      this.popupShow = false;
      let postData = this.mapChartOption.series[1].data


      let sortARRAY = [
        {
          name: '玄武区',
          po: 117.50178199381502,
        },
        {
          name: "秦淮区",
          po: 117.80275088312039,
        },

        {
          name: "栖霞区",
          po: 118.0700171677927,
        },
        {
          name: "江宁区",
          po: 118.34517124315529,
        },
        {
          name: "鼓楼区",
          po:
            120.02,
        },
        {
          name: "浦口区",
          po: 119.42,
        },
        {
          name: "雨花台区",
          po:
            119.72748167619326,
        },
        {
          name: "建邺区",
          po:
            119.14198405255736,
        },
        {
          name: "南京",
          po: 119.60112051295135,
        },
      ]

      postData.forEach(it => {
        sortARRAY.forEach(et => {
          if (it.name == et.name) {
            it.coords[1][0] = et.po
          }
        })
      })

      // 

      console.log(postData, '看最后的值');
      this.mapChartOption.series[1].data = postData

      console.log(this.mapChartOption.series[1].data, '看地图上的值');

      // postData[0].coords[0][0] = 240
      // postData[0].coords[0][1] = 240

      let myData = this.mapChartOption.series[1].data
      if (!this.is_clickTimeline) {
        adjustResourceMap(this.mapParams).then(res => {
          if (res.code !== 200) return

          res.data.forEach(it => {
            if (it.area_name == '南京') {
              this.nanjingData.up = Number(it.margin_up).toFixed(2)
              this.nanjingData.lower = Number(it.margin_down).toFixed(2)
              this.nanjingData.num = Number(it.resource_size)
            }
          })

          myData.forEach(it => {
            res.data.forEach(et => {
              if (it.name == et.area_name) {
                it.info.up = Number(et.margin_up).toFixed(2)
                it.info.lower = Number(et.margin_down).toFixed(2)
                it.info.num = et.resource_size
              }
            })
          })

          // myData.forEach(it=>{
          //   if(it.name == '南京'){
          //     console.log(it.info ,'看info');

          //     this.nanjingData = it.info
          //   }
          // })

          this.mapChartOption.series[1].data = myData.filter((it) => it.name != '南京')

          console.log(myData, 'kanmyDta');

          this.initMyMap()
        })
      } else {

        adjustResourceMapByTime(this.mapParams).then(res => {
          if (res.code !== 200) return

          res.data.forEach(it => {
            if (it.area_name == '南京') {
              this.nanjingData.up = Number(it.margin_up).toFixed(2)
              this.nanjingData.lower = Number(it.margin_down).toFixed(2)
              this.nanjingData.num = Number(it.resource_size)
            }
          })

          myData.forEach(it => {
            res.data.forEach(et => {
              if (it.name == et.area_name) {

                it.info.up = Number(et.margin_up).toFixed(2)
                it.info.lower = Number(et.margin_down).toFixed(2)
                it.info.num = et.resource_size
              }
            })
          })

          // myData.forEach(it=>{
          //   if(it.name == '南京'){
          //     console.log(it.info ,'看info');
          //     this.nanjingData = it.info
          //   }
          // })

          this.mapChartOption.series[1].data = myData.filter((it) => it.name != '南京')
          console.log(myData, 'kanmyDta');
          this.initMyMap()
        })
      }

    },



    initMyMap() {
      let parentMapJson = require('@/utils/home/mapJson/nanjing.json');
      let cityItem = parentMapJson.features.find((x) => x.properties.name == "玄武区");  //这边这个位置应该不能写死
      this.mapChart.setOption(this.mapChartOption);
    },




    setRowClass({ row, rowIndex }) {
      if (row.type == '储') {
        return { 'color': '#05a4e7' };
      } else if (row.type == '源') {
        return { 'color': '#af9d24' };
      } else if (row.type == '荷') {
        return { 'color': '#00706b' };
      } else if (row.type == '新能源') {
        return { 'color': '#0972e0' };
      }
    },
    popupChartClose() {
      this.popupShow = false;
    }
  },
  components: {},
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}



.el-table--border {
  border-right: 1px solid #0c8f96;
}

.container_main {
  position: relative;
  display: flex;


}

.container_right {
  .title {
    width: 100%;
    height: 34px;
    line-height: 34px;
    padding-left: 47px;
    padding-right: 20px;
    box-sizing: border-box;
    color: #00706b;
    font-size: 18px;
    font-weight: bold;
    background: url(../../../assets/images/views/home/titleBg.png) left center no-repeat;

    span {
      font-size: 12px;
      float: right;
      color: #333;
      font-weight: normal;
    }
  }

  .container_top {
    width: 760px;
    height: 470px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
  }

  .part-top {
    width: 100%;
    display: flex;
  }

  .part-bottom {
    width: 100%;
  }

  .container_bottom {
    width: 760px;
    height: 450px;
    padding: 10px 15px;
    background: url(../../../assets/images/phyd_bg.png) no-repeat;
    background-size: 100% 100%;
  }

  .part {
    background: url(../../../assets/images/phyd_bg.png) no-repeat;
    background-size: 100% 100%;
    padding: 10px 15px;
  }

  .part1 {
    width: 760px;
    height: 210px;
  }

  .part2 {
    width: 280px;
    height: 250px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .part3 {
    width: 480px;
    height: 250px;
  }

  .part4 {
    width: 100%;
    height: 100%;
  }

  .flex-row {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    height: 100px;
  }

  .row-img {
    width: 60px;
    height: 60px;
    margin-left: 10px;
    margin-right: 20px;
  }

  .row-data {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
  }

  .row-title {
    width: 160px;
    height: 25px;
    line-height: 25px;
    padding-left: 20px;
    background: url(../../../assets/images/part-bg.png) center bottom no-repeat;
    background-size: 100% 100%;
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 16px;
    color: #2D3B4D;
  }

  .row-info {
    width: 100%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-family: DINPro;
    font-weight: bold;
    font-size: 22px;
    color: #2D3B4D;
  }
}

.container_left {
  width: 1115px;
  height: 930px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  position: relative;

  .nanjingCard {
    border-radius: 4px;
    overflow: hidden;

    position: absolute;
    right: 127px;
    top: 96px;
    width: 104px;
    height: 90px;
    // background-color: red;
    background-color: #c8f0f0;

    text-align: center;
    font-size: 12px;

    .title {
      background-color: #bce0e1;
      font-size: 16px;
      line-height: 25px;
      border-bottom: 2px solid rgba(119, 119, 119, 0.2);
    }

    // hr {
    //   background-color: #777;
    //   width: '100%';
    //   border-width: 0.5;
    //   height: 0;
    //   text-align: left;
    // }



    .content {
      letter-spacing: 1px;

      .down {
        margin: 2px 0;
        white-space: nowrap;

      }

      .up {
        white-space: nowrap;

      }

      .num {
        white-space: nowrap;
      }
    }
  }
}

.tab-panel {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 20px;
}

.option-btn {
  display: block;
  width: 80px;
  height: 35px;
  border: 1px dashed #00706B;
  line-height: 35px;
  text-align: center;
  /* border-radius: 12px; */
  cursor: pointer;
  font-size: 14px;
  background-color: #C5FCFF;
  color: #00706B;
}

.btnSelected {
  background-color: #00706B;
  color: #ffffff;
}

.map-panel {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  width: 100%;
  height: 100%;
}

.timeline-wrap {
  background: url(../../../assets/images/timeline-bg.png) left top no-repeat;
  background-size: 68px 20px;
  padding-top: 1px;
  position: relative;
  padding-bottom: 8px;
}

.timeline-wrap2 {

  background: url(../../../assets/images/bacolor.png) left top no-repeat;
  background-size: 68px 20px;
  padding-top: 1px;
  position: relative;
  padding-bottom: 8px;
}

.timeline-abs {
  position: absolute;
  left: -3px;
  top: -8px;
  width: 32px;
  height: 24px;
  opacity: 0.7;
  border-radius: 5px;
}

.abs-red {
  background-image: linear-gradient(to left, #eee, #C63C63);
  border: 1px #a10c35;
}

.abs-yellow {
  background-image: linear-gradient(to left, #eee, #eee327);
  border: 1px #989007;
}

.timeline-icon {
  position: absolute;
  left: 0px;
  top: -3px;
  width: 14px;
  height: 14px;
}

.timeline-legend {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  font-size: 14px;
  color: #4A4A4A;
  padding-left: 40px;

  div {
    background-size: 20px auto;
    padding-left: 23px;
  }

  .status1 {
    background: url(../../../assets/images/status1.png) left center no-repeat;
  }

  .status2 {
    background: url(../../../assets/images/status2.png) left center no-repeat;
  }

  .type1 {
    background: url(../../../assets/images/icon-top.png) left center no-repeat;
  }

  .type2 {
    background: url(../../../assets/images/icon-bottom.png) left center no-repeat;
  }
}

.chart-float {
  position: absolute;
  z-index: 99;
  background-color: rgb(255, 255, 255, 0.8);
  left: calc(50% - 190px);
  top: calc(40% - 140px);
  width: 380px;
  height: 280px;
  padding: 10px;
  border: 1px solid #2eadd3;
  border-radius: 10px;
  box-shadow: 10px 10px 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;

  .title {
    width: 100%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-bottom: 1px solid #2eadd3;
    color: #2D3B4D;
    font-size: 16px;
    font-weight: 600;

    .close {
      float: right;
      width: 20px;
      height: 20px;
      line-height: 20px;
      border: 1px solid #2e6e6a;
      border-radius: 20px;
      cursor: pointer;
      color: #2e6e6a;
    }
  }

  .chart {
    width: 100%;
    height: calc(100% - 30px);
  }
}


.timeline {
  position: relative;
  width: 100%;
  //height: 750px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}


.myslider {
  width: 100%;
  height: 720px;
  position: absolute;

  left: 26px;
  top: 8px;
  z-index: 10;
  opacity: 0.8;
}




.mytooltip {
  position: absolute;
  z-index: 2;
  left: 42px;
  width: 140px;
  height: 30px;
  line-height: 30px;
  background: url("../../../assets/images/currenttime-bg.png") center no-repeat;
  background-size: 100% 100%;
  border-radius: 4px;
  padding-right: 12px;
  color: #ffffff;
  font-weight: 500;
  text-align: right;
}

::v-deep .el-slider.is-vertical .el-slider__runway {
  width: 6px;
  height: 100%;
  margin: 0 16px;
  background-color: transparent;
  border-radius: 3px;
  position: relative;
  cursor: pointer;
  vertical-align: middle;
}

::v-deep .el-slider.is-vertical .el-slider__bar {
  width: 6px;
  height: auto;
  border-radius: 0 0 3px 3px;
  background-color: transparent;
}

::v-deep .el-slider__button {
  width: 150px;
  height: 30px;
  //border: solid 2px #000;
  //background-color: #000;
  //border-radius: 50%;
  border: none;
  border-radius: 0;
  background-color: transparent;
  -webkit-transition: 0.2s;
  transition: 0.2s;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}



::v-deep .el-dropdown-menu {
  z-index: 888;
}
</style>
